import { Button, message } from 'antd';
import { useEffect, useState } from 'react';

let timer: any = null;
const CountDownButton = (props: { getCaptchaFn: () => Promise<any> }) => {
  const { getCaptchaFn } = props;
  const [countDown, setCountDown] = useState(60);
  const [disable, setDisable] = useState(false);
  useEffect(() => {
    if (disable) {
      timer = setInterval(() => {
        setCountDown((countDown: number) => {
          if (countDown === 1) {
            setDisable(false);
            clearInterval(timer);
            return 60;
          }
          return countDown - 1;
        });
      }, 1000);
    }
  }, [disable]);

  return (
    <Button
      disabled={disable}
      onClick={async () => {
        try {
          const res = (await getCaptchaFn()) as any;
          if (res.success) {
            setDisable(true);
            message.success('发送成功');
          } else {
            message.error('发送验证码失败');
          }
        } catch (error) {
          message.error('发送验证码失败');
        }
      }}
    >
      {disable ? `${countDown}秒后重新发送` : '发送验证码'}
    </Button>
  );
};

export default CountDownButton;
